/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.handlers.classifiers;

import net.sourceforge.wurfl.core.handlers.Handler;

import org.apache.commons.lang.text.StrBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * {@link Filter} base implementation.
 * 
 * <p>
 * The {@link Handler} decides if this object can handle the given user-agent.
 * Stores the classified device in held {@link FilteredDevices} instance.
 * </p>
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: BaseFilter.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class BaseFilter implements Filter {

	/** Classified device identifiers */
	private final FilteredDevices filteredDevices;

	/** The held Handler */
	private final Handler handler;

	/** Log */
	private static final Log log = LogFactory.getLog(BaseFilter.class);

	/**
	 * Constructor by {@link Handler} and {@link FilteredDevices}.
	 * 
	 * @param handler
	 *            The handler used by this object.
	 * @param filteredDevices
	 *            The FilteredDevices used to classify devices.
	 *            identifier by user-agent.
	 */
	public BaseFilter(Handler handler) {
		this.handler = handler;
		this.filteredDevices = new FilteredDevices();
	}

	/**
	 * Use the Handler to know if is possible to handle the user-agent.
	 */
	public boolean canHandle(String userAgent) {
		return handler.canHandle(userAgent);
	}

	/**
	 * Add the given device id and user-agent to collected devices.
	 */
	public void filter(String userAgent, String deviceID) {

		if (log.isTraceEnabled()) {
			StrBuilder logBuilder = new StrBuilder();
			logBuilder.append("Putting Device: ").append(deviceID).append(
					" into filter");
			log.trace(logBuilder.toString());
		}

		this.filteredDevices.putDevice(userAgent, deviceID);
	}

	/**
	 * Return the held {@link FilteredDevices}.
	 */
	public FilteredDevices getFilteredDevices() {
		return filteredDevices;
	}
}
